package daos;


import entitys.Campeonato;
import entitys.HistoricoPartida;
import entitys.Partida;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import utils.JpaUtils;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Amauri
 */
public class HistoricoDAO {
    
    public HistoricoDAO(){}
    
    public void persistir(HistoricoPartida hist){
    
        if (hist.getID() == null){
            this.insert(hist);
        }else{
            this.update(hist);
        }
    }
    
    public void insert(HistoricoPartida hist) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.persist(hist);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    public void update(HistoricoPartida hist) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.merge(hist);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
            
    public void delete(HistoricoPartida hist) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            hist = manager.merge(hist);
            manager.remove(hist);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public HistoricoPartida findById(Long id) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            return manager.find(HistoricoPartida.class, id);
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public List<HistoricoPartida> listAll(Partida part) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            Query query = manager.createQuery("select c from HistoricoPartida c where c.partida.ID = " + part.getID(), HistoricoPartida.class);
            return query.getResultList();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
}
